<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/9/28
 * Time: 11:25
 */

namespace Home\Controller;


use Admin\Enums\AuthorType;
use Home\Service\ImageSheetService;
use Home\Service\MemberSheetViewListService;
use Home\Service\ScoreService;
use Home\Service\ScoreSheetService;
use Home\Service\SheetFavoriteService;

class SheetController extends HomeController
{
    /**
     * 获取曲谱详情
     */
    public function index()
    {
        $param = I('param.');
        $uid = $param['uid'] ?: 0;
        $id = $param['id'];
        if (!empty($id) && is_numeric($id)) {
            //1.获取曲谱信息
            $map = array(
                'id' => $id,
                'is_delete' => 0
            );
            $sheet = M('sheet')->where($map)->find();
            //2.获取创建者信息
            /*if ($sheet['author_type'] == AuthorType::$ADMIN) {
                $userInfo = M('Member')->where(array('uid' => $sheet['creator']))->find();
                $sheet['creator_info']['nickname'] = $userInfo['nickname'];
            } else {*/
                $userInfo = M('User')->where(array('id' => $sheet['creator']))->find();
                $sheet['creator_info']['nickname'] = $userInfo['nickname'];
                $sheet['creator_info']['avatar_url'] = $userInfo['avatar_url'];
            //}
            //3.获取曲谱图片
            $map = array(
                'ish.sheet_id' => $id,
                'ish.is_delete' => 0
            );
            $join = 'image i ON ish.image_id = i.id';
            $sheetImgs = M('ImageSheet')->alias('ish')->field('i.id, i.name, i.url, i.creator, i.listorder')->join($join)->where($map)->order('i.listorder, i.id')->select();

            //4.获取曲谱图片设置
            $service = new ImageSheetService();
            $imgConfigs = $service->sheetImgConfig($id);
            if (!empty($imgConfigs)) {
                foreach ($sheetImgs as $key => $sheetImg) {
                    $sheetImgs[$key]['scale'] = $imgConfigs[$sheetImg['id']]['scale'];
                }
            }
            $sheet['image'] = $sheetImgs;
            //5.记录会员用户浏览曲谱次数流水
            if ($uid) {
                $map = [
                    'user_id' => $uid,
                    'amount' => ['gt', 0]
                ];
                $isMember = M('UserCoinWallet')->where($map)->find(); //验证是否会员
                if ($isMember) {
                    $MSVLService = new MemberSheetViewListService();
                    $res = $MSVLService->add($uid, $id); //写入浏览流水
                    if ($res) {
                        M('UserCoinWallet')->where(['user_id' => $uid])->setInc('sheet_click');  //更新查阅量
                        //判断是否满足升级条件
                        $set = M('UserMemberLevels')->where(['level' => $isMember['member_level']])->find();
                        if ($isMember['member_days'] >= $set['member_days'] && ($isMember['sheet_click'] + 1 ) >= $set['sheet_click']) {
                            M('UserCoinWallet')->where(['user_id' => $uid])->setInc('member_level');
                            //todo 触发升级通知
                        }
                    }
                }
            }
            //6.获取用户是否喜欢曲谱
            $favStatus = M('SheetFavorite')->where(['user_id'=> $uid, 'sheet_id'=> $id, 'is_delete'=> 0])->find();
            $sheet['fav_status'] = $favStatus ? 1 : 0;
            $this->assign('sheet', $sheet);
        }
        $this->display();
    }

    /**
     * 曲谱展示设置
     */
    public function displayConfig()
    {
        $data = I('param.');
        $sheetId = (int)$data['sheet_id'];
        unset($data['sheet_id']);
        $userInfo = session('user');
        foreach ($data as $key => $val) {
            $img[] = array(
                'sheet_id' => $sheetId,
                'image_id' => $key,
                'user_id' => empty($userInfo) ? 0 : $userInfo['uid'],
                'width' => (float)$val[0],
                'height' => (float)$val[1],
                'scale' => (float)((float)$val[0] / (float)$val[1]),
            );
        }

        $map = array(
            'user_id' => empty($userInfo) ? 0 : $userInfo['uid'],
            'sheet_id' => $sheetId
        );
        $config = M('ImageUserConfig')->where($map)->find();
        if (!empty($config)) {
            foreach ($img as $val) {
                $map = array(
                    'user_id' => empty($userInfo) ? 0 : $userInfo['uid'],
                    'image_id' => $val['image_id']
                );
                $res[] = M('ImageUserConfig')->where($map)->save($val);
            }
        } else {
            $res = M('ImageUserConfig')->addAll($img);
        }

        if ($res) {
            $return['code'] = 200;
            $return['msg'] = '设置成功';
            $this->ajaxReturn($return);
        } else {
            $return['code'] = 0;
            $return['msg'] = '失败';
            $this->ajaxReturn($return);
        }
    }

    /**
     * 喜欢曲谱
     */
    public function favSheet()
    {
        $data = I('param.');
        $user = session('user');
        if (empty($user)) {
            $return['code'] = 10001;
            $return['msg'] = '请先登录';
            $this->ajaxReturn($return);
        }
        $data['user_id'] = $user['uid'];
        $favService = new SheetFavoriteService();
        $res = $favService->favSheet($data);
        if ($res) {
            $return['code'] = 200;
            $return['msg'] = 'success';
            $this->ajaxReturn($return);
        } else {
            $return['code'] = 0;
            $return['msg'] = 'failed';
            $this->ajaxReturn($return);
        }
    }

    /**
     * 收藏曲谱
     */
    public function collectSheet()
    {
        $param = I('param.');
        $user = session('user');
        if (empty($param['sheet_id']) || empty($param['score_id'])) {
            $return['code'] = 600;
            $return['msg'] = '缺少必要参数';
            $this->ajaxReturn($return);
        }
        $param['creator'] = $user['uid'];
        $service = new ScoreSheetService();
        try {
            $res = $service->addSheetToScore( $param );
            if ($res == 500) {
                $return['code'] = 500;
                $return['msg'] = '曲谱已存在';
                $this->ajaxReturn($return);
            } elseif (!$res) {
                $return['code'] = 500;
                $return['msg'] = '收藏失败';
                $this->ajaxReturn($return);
            }
            $return['code'] = 200;
            $return['msg'] = '收藏成功';
            $this->ajaxReturn($return);
        } catch (\Exception $e) {
            $return['code'] = 500;
            $return['msg'] = $e->getMessage();
            $this->ajaxReturn($return);
        }
    }

    /**
     * 新建谱单并收藏
     */
    public function newScoreAndFav()
    {
        $param = I('param.');
        $user = session('user');
        //新建谱单
        $data['name'] = trim($param['name']);
        $data['creator'] = $user['uid'];
        $service = new ScoreService();
        $scoreId = $service->add($data);

        //保存谱单曲谱关系
        $newData['score_id'] = $scoreId;
        $newData['sheet_id'] = $param['sheet_id'];
        $newData['creator']  = $user['uid'];
        $scoShService = new ScoreSheetService();
        try {
            $res = $scoShService->addSheetToScore($newData);
            if (!$res) {
                $return['code'] = 500;
                $return['msg'] = '收藏失败';
                $this->ajaxReturn($return);
            }
            $return['code'] = 200;
            $return['msg'] = '收藏成功';
            $this->ajaxReturn($return);
        } catch (\Exception $e) {
            $return['code'] = 500;
            $return['msg'] = $e->getMessage();
            $this->ajaxReturn($return);
        }
    }
}